<template>
  <div class="table-box">
    <!-- 搜索表单 -->
    <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
      <el-form-item label="组织名称" prop="orgName">
        <el-input v-model="searchForm.orgName" placeholder="请输入组织名称" clearable />
      </el-form-item>
      <el-form-item label="组织类型" prop="orgType">
        <el-select v-model="searchForm.orgType" placeholder="请选择组织类型" clearable style="width: 180px">
          <el-option label="公司" value="COMPANY" />
          <el-option label="部门" value="DEPARTMENT" />
          <el-option label="车间" value="WORKSHOP" />
          <el-option label="班组" value="TEAM" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 180px">
          <el-option label="启用" value="ACTIVE" />
          <el-option label="禁用" value="INACTIVE" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-header">
      <el-button type="primary" :icon="CirclePlus" @click="handleAdd">新增组织</el-button>
      <el-button type="success" @click="handleExpandAll">展开全部</el-button>
      <el-button type="warning" @click="handleCollapseAll">收起全部</el-button>
    </div>

    <el-table 
      :data="tableData" 
      style="width: 100%" 
      v-loading="loading" 
      border
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :expand-row-keys="expandedKeys"
      @expand-change="handleExpandChange"
    >
      <el-table-column prop="orgName" label="组织名称" width="300">
        <template #default="scope">
          <span>{{ scope.row.orgName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="orgCode" label="组织编码" />
      <el-table-column prop="orgType" label="组织类型">
        <template #default="scope">
          <el-tag :type="getOrgTypeTag(scope.row.orgType)">{{ getOrgTypeText(scope.row.orgType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="leader" label="负责人" />
      <el-table-column prop="phone" label="联系电话" />
      <el-table-column prop="memberCount" label="人员数量" align="center">
        <template #default="scope">
          <el-badge :value="scope.row.memberCount" class="member-badge" />
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" align="center" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
          <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="success" link @click="handleAddChild(scope.row)">添加下级</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts" name="systemOrganization">
import { ref, reactive, onMounted } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus } from "@element-plus/icons-vue";

const loading = ref(false);
const tableData = ref([]);
const searchFormRef = ref<FormInstance>();
const expandedKeys = ref<string[]>([]);

// 查询表单
const searchForm = reactive({
  orgName: "",
  orgType: "",
  status: ""
});

// 获取组织类型标签
const getOrgTypeTag = (type: string) => {
  const typeMap: Record<string, string> = {
    COMPANY: "primary",
    DEPARTMENT: "success",
    WORKSHOP: "warning",
    TEAM: "info"
  };
  return typeMap[type] || "info";
};

// 获取组织类型文本
const getOrgTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    COMPANY: "公司",
    DEPARTMENT: "部门",
    WORKSHOP: "车间",
    TEAM: "班组"
  };
  return typeMap[type] || type;
};

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    ACTIVE: "success",
    INACTIVE: "warning"
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    ACTIVE: "启用",
    INACTIVE: "禁用"
  };
  return statusMap[status] || status;
};

// 获取表格数据
const getTableData = async () => {
  loading.value = true;
  try {
    // 模拟树形数据
    const mockData = [
      {
        id: "1",
        orgCode: "COMP001",
        orgName: "智能制造有限公司",
        orgType: "COMPANY",
        leader: "王总",
        phone: "021-12345678",
        memberCount: 500,
        status: "ACTIVE",
        sort: 1,
        createTime: "2024-01-01 00:00:00",
        children: [
          {
            id: "2",
            orgCode: "DEPT001",
            orgName: "生产部",
            orgType: "DEPARTMENT",
            leader: "张部长",
            phone: "021-12345679",
            memberCount: 150,
            status: "ACTIVE",
            sort: 1,
            createTime: "2024-01-01 00:00:00",
            children: [
              {
                id: "5",
                orgCode: "WS001",
                orgName: "装配车间",
                orgType: "WORKSHOP",
                leader: "李主任",
                phone: "021-12345681",
                memberCount: 80,
                status: "ACTIVE",
                sort: 1,
                createTime: "2024-01-01 00:00:00",
                children: [
                  {
                    id: "8",
                    orgCode: "TEAM001",
                    orgName: "装配一班",
                    orgType: "TEAM",
                    leader: "赵班长",
                    phone: "13800138001",
                    memberCount: 25,
                    status: "ACTIVE",
                    sort: 1,
                    createTime: "2024-01-01 00:00:00"
                  },
                  {
                    id: "9",
                    orgCode: "TEAM002",
                    orgName: "装配二班",
                    orgType: "TEAM",
                    leader: "钱班长",
                    phone: "13800138002",
                    memberCount: 25,
                    status: "ACTIVE",
                    sort: 2,
                    createTime: "2024-01-01 00:00:00"
                  }
                ]
              },
              {
                id: "6",
                orgCode: "WS002",
                orgName: "机加车间",
                orgType: "WORKSHOP",
                leader: "王主任",
                phone: "021-12345682",
                memberCount: 70,
                status: "ACTIVE",
                sort: 2,
                createTime: "2024-01-01 00:00:00"
              }
            ]
          },
          {
            id: "3",
            orgCode: "DEPT002",
            orgName: "质量部",
            orgType: "DEPARTMENT",
            leader: "刘部长",
            phone: "021-12345680",
            memberCount: 50,
            status: "ACTIVE",
            sort: 2,
            createTime: "2024-01-01 00:00:00"
          },
          {
            id: "4",
            orgCode: "DEPT003",
            orgName: "技术部",
            orgType: "DEPARTMENT",
            leader: "陈部长",
            phone: "021-12345681",
            memberCount: 80,
            status: "ACTIVE",
            sort: 3,
            createTime: "2024-01-01 00:00:00"
          }
        ]
      }
    ];
    
    tableData.value = mockData;
  } catch (error) {
    console.error("获取组织架构失败:", error);
    ElMessage.error("获取组织架构失败");
  } finally {
    loading.value = false;
  }
};

// 查询
const handleSearch = () => {
  getTableData();
};

// 重置
const handleReset = () => {
  if (!searchFormRef.value) return;
  searchFormRef.value.resetFields();
  getTableData();
};

// 展开全部
const handleExpandAll = () => {
  const getAllKeys = (data: any[]): string[] => {
    let keys: string[] = [];
    data.forEach(item => {
      keys.push(item.id);
      if (item.children && item.children.length > 0) {
        keys = keys.concat(getAllKeys(item.children));
      }
    });
    return keys;
  };
  expandedKeys.value = getAllKeys(tableData.value);
};

// 收起全部
const handleCollapseAll = () => {
  expandedKeys.value = [];
};

// 展开/收起事件
const handleExpandChange = (row: any, expanded: boolean) => {
  if (expanded) {
    if (!expandedKeys.value.includes(row.id)) {
      expandedKeys.value.push(row.id);
    }
  } else {
    const index = expandedKeys.value.indexOf(row.id);
    if (index > -1) {
      expandedKeys.value.splice(index, 1);
    }
  }
};

// 新增组织
const handleAdd = () => {
  ElMessage.info("新增组织功能开发中");
};

// 查看详情
const handleView = (row: any) => {
  ElMessage.info(`查看组织 ${row.orgName} 详情`);
};

// 编辑组织
const handleEdit = (row: any) => {
  ElMessage.info(`编辑组织 ${row.orgName}`);
};

// 添加下级组织
const handleAddChild = (row: any) => {
  ElMessage.info(`为 ${row.orgName} 添加下级组织`);
};

// 删除组织
const handleDelete = async (row: any) => {
  ElMessageBox.confirm(`确认删除组织 "${row.orgName}" 吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        ElMessage.success("组织删除成功");
        getTableData();
      } catch (error) {
        console.error("组织删除失败:", error);
        ElMessage.error("组织删除失败");
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 页面加载时获取数据
onMounted(() => {
  getTableData();
});
</script>

<style scoped>
.search-form {
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.table-header {
  margin-bottom: 16px;
  display: flex;
  gap: 10px;
}

.member-badge {
  margin-right: 10px;
}
</style>